package io.hellsinger.filesystem.linux.operation

import io.hellsinger.filesystem.checkScheme
import io.hellsinger.filesystem.directory.Directory
import io.hellsinger.filesystem.file.File
import io.hellsinger.filesystem.linux.LinuxFileOperationProvider
import io.hellsinger.filesystem.linux.LinuxOperationOptions
import io.hellsinger.filesystem.linux.error.ErrnoException
import io.hellsinger.filesystem.path.Path

fun <P : Path> Directory<P>.create(mode: Int = DEFAULT_OPEN_MODE) {
    checkScheme(LinuxOperationOptions.SCHEME)

    LinuxFileOperationProvider.makeDirectory(path.bytes, mode)
}

@Throws(ErrnoException::class)
fun <P : Path> File<P>.create(mode: Int = DEFAULT_OPEN_MODE) {
    checkScheme(LinuxOperationOptions.SCHEME)

    val fd =
        LinuxFileOperationProvider.openFileDescriptor(
            path.bytes,
            LinuxOperationOptions.Open.CREATE_NEW,
            mode,
        )

    LinuxFileOperationProvider.closeFileDescriptor(fd)
}

fun <P : Path> File<P>.truncate(mode: Int = DEFAULT_OPEN_MODE) {
    checkScheme(LinuxOperationOptions.SCHEME)

    val fd =
        LinuxFileOperationProvider.openFileDescriptor(
            path.bytes,
            LinuxOperationOptions.Open.TRUNCATE,
            mode,
        )

    LinuxFileOperationProvider.closeFileDescriptor(fd)
}
